package lyl.servlet;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防SQL注入攻击
 * 
 * @author lyl
 *
 */
public class SQLFilter implements Filter {

	protected String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";
	protected String error_jsp = "sof_error.jsp";
	
	protected FilterConfig filterConfig = null;

	/**
	 * Should a character encoding specified by the client be ignored?
	 */
	protected boolean ignore = true;

	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
		this.inj_str = filterConfig.getInitParameter("keywords");
		this.error_jsp = filterConfig.getInitParameter("errorjsp");
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response; 
		Iterator values = req.getParameterMap().values().iterator();
		while(values.hasNext()){
			String[] value = (String[])values.next();
			for(int i = 0;i < value.length;i++){
				if(sql_inj(value[i])){
					res.sendRedirect(req.getContextPath()+this.error_jsp);
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}
	
	public boolean sql_inj(String str)
	{
	    String inj_str = "'|drop|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";//这里的东西还可以自己添加
	    String[] inj_stra=inj_str.split("\\|");
	    for (int i=0 ; i < inj_stra.length ; i++ )
	    {
	        if (str.indexOf(" "+inj_stra[i]+" ")>=0)
	        {
	        	System.out.println("str========="+str);
	        	System.out.println("inj_stra========="+inj_stra[i]);
	            return true;
	        }
	    }
	    return false;
	}

	public void destroy() {
		this.inj_str = null;
		this.filterConfig = null;
	}

	public FilterConfig getFilterConfig() {
		//TODO Method stub generated by Lomboz
		return null;
	}

	public void setFilterConfig(FilterConfig config) {
		//TODO Method stub generated by Lomboz
	}
}
